import { Space, Button, message, Modal, Typography, } from 'antd';
import ProCard from '@ant-design/pro-card';
import React, { useState, useRef, useEffect } from 'react';
import { getDvaApp, history, } from 'umi';
import ProForm, {
    ProFormText,
    ProFormSelect,
} from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import $utils from '@/utils/utils';
import { ImeiCreate, getImeiDetail, ImeiGenCode } from '@/services/imei';
import { getAgentList } from '@/services/agent';
import { equipmentTypes, brandNames, modelTypes, hardwareVersion, cellCodeTypeData, mainBoardData } from '@/utils/common';
import { QuestionCircleOutlined } from '@ant-design/icons';

const { Title, Paragraph, Text, Link } = Typography;

const Detail: React.FC = () => {

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;
    const formRef = useRef<ProFormInstance>();
    const [explain_visible, setExplain_visible] = useState<boolean>(false);

    // 设备类型
    const [deviceType, setDeviceType] = useState<number>(1);
    // 设备类型
    const [modelType, setModelType] = useState<number>();

    const [cur_id, setCur_id] = useState<string>();
    const [imeiDetail, setImeiDetail] = useState<any>();
    const [agentList, setAgentList] = useState<any>();
    const [cur_hwareVersion, setHwareVersion] = useState<string>('');

    const l_state: any = history.location.state;
    if (!cur_id && !l_state) {
        history.push('/BasicConfig/IMEI');
    }

    const id: string = l_state?.data?.id || '';
    //  同path更新,只更新state时，通过id重新请求数据
    if ((l_state && id) && (!cur_id || cur_id !== id)) {
        console.log('state', l_state);
        setCur_id(id);
    } else if (l_state && !id && cur_id !== id) {
        setCur_id('');
    }

    const isCreate: boolean = l_state?.status === 'create';
    const isDetail: boolean = l_state?.status === 'detail';

    useEffect(() => {
        const getAgentData = async () => {
            try {
                const msg = await getAgentList({ name: '', pageSize: 1000 });
                let new_data: API.Select[] = [];
                if (msg.code === 0) {
                    msg.body.list.map((item: { id: number, name: string }) => {
                        new_data.push({
                            label: item.name,
                            value: item.id,
                        });
                    });
                    setAgentList(new_data);
                    return;
                }
            } catch (error) {
                console.log(error);
                message.error('代理商列表获取失败!');
            }
        };
        getAgentData();
    }, []);


    useEffect(() => {
        const getImeiData = async () => {
            try {
                const msg = await getImeiDetail({ id: id });
                if (msg.code === 0) {
                    const imeiDetail = msg.body;
                    if (!imeiDetail.stationName) {
                        imeiDetail.stationName = '无';
                    }
                    setHwareVersion(msg.body.hwareVersion);
                    setDeviceType(msg.body.type);
                    setImeiDetail(imeiDetail);
                    formRef && formRef.current?.resetFields();

                    return;
                }
            } catch (error) {
                console.log(error);
            }
        };
        if (!cur_id) {
            setImeiDetail(undefined);
            formRef && formRef.current?.resetFields();
        }
        else {
            getImeiData();
            return;
        }
    }, [cur_id]);

    const getAuthCode = async (id: number) => {
        try {
            const msg = await ImeiGenCode({ agentId: id });
            if (msg.code === 0) {
                formRef?.current?.setFieldValue('authCode', msg.body.authCode);
                formRef?.current?.setFieldValue('code', msg.body.cabCode);
                return;
            } else {
                formRef?.current?.setFieldValue('authCode', '');
                formRef?.current?.setFieldValue('code', '');
            }
        } catch (error) {
            console.log(error);
        }
    };

    return (
        <PageContainer>
            {(isCreate || imeiDetail) && <ProCard style={{ marginTop: 8 }} gutter={8} >
                <ProForm
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 16 }}
                    layout={"horizontal"}
                    formRef={formRef}
                    initialValues={isCreate ? undefined : imeiDetail}
                    onFinish={async (values) => {
                        let params = { ...values };
                        if (values.type === 3) {
                            const agent = agentList.find((item: any) => item.value === values.agentName);
                            params.agentName = agent.label;
                            params.agentId = agent.value;
                        }
                        // console.log(params);
                        if (isCreate) {
                            const msg = await ImeiCreate(params);
                            if (msg.code === 0) {
                                message.success('新增成功', 1, () => {
                                    // 设置当前tab对象
                                    $utils.setNewTab(dispatch, { name: 'IMEI管理', path: '/BasicConfig/IMEI', isTopMenu: true });
                                    history.push('/BasicConfig/IMEI');
                                });
                            }
                        }
                    }}
                    onFinishFailed={(error: any) => {
                        console.error(error);
                    }}
                    submitter={{
                        render: (props, doms) => {
                            return [
                                <Space style={{ marginLeft: '16.66666667%' }}>
                                    {isCreate && <Button type="primary" htmlType="submit">保存</Button>}
                                    <Button onClick={() => {
                                        // 设置当前tab对象
                                        $utils.setNewTab(dispatch, { name: 'IMEI管理', path: '/BasicConfig/IMEI', isTopMenu: true });
                                        history.push('/BasicConfig/IMEI');
                                    }}>取消</Button>
                                </Space>
                            ]
                        }
                    }}
                >
                    <ProFormSelect
                        width={'md'}
                        name="type"
                        label={'设备类型'}
                        disabled={isDetail}
                        rules={[
                            {
                                required: true,
                                message: '请选择设备类型'
                            }
                        ]}
                        fieldProps={{
                            options: equipmentTypes,
                            onChange: (value: any) => {
                                setDeviceType(value);
                                if (value === 3) {
                                    const cur_model = formRef?.current?.getFieldValue('model');
                                    console.log(cur_model);
                                    !cur_model && formRef?.current?.setFieldValue('model', 3);
                                }
                            }
                        }}
                    />
                    {deviceType !== 2 && <ProFormSelect
                        width={'md'}
                        name="model"
                        label={'设备型号'}
                        disabled={isDetail}
                        rules={[
                            {
                                required: true,
                                message: '请选择设备型号'
                            }
                        ]}
                        fieldProps={{
                            options: deviceType === 1 ? modelTypes.slice(0, 2) : modelTypes.slice(-2),
                            onChange: (value: any) => {
                                setModelType(value);
                            }
                        }}
                    />}
                    {deviceType !== 3 && <ProFormText
                        width={'md'}
                        name="imei"
                        label={'IMEI'}
                        disabled={isDetail}
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                    />}
                    {deviceType === 3 && <ProFormSelect
                        width={'md'}
                        name="brand"
                        label={'设备品牌'}
                        disabled={isDetail}
                        rules={[
                            {
                                required: true,
                                message: '请选择设备品牌'
                            }
                        ]}
                        fieldProps={{
                            options: brandNames,
                        }}
                    />}
                    {deviceType === 3 && <ProFormSelect
                        width={'md'}
                        name="agentName"
                        label={'代理商名称'}
                        disabled={isDetail}
                        rules={[
                            {
                                required: true,
                                message: '请选择代理商名称'
                            }
                        ]}
                        fieldProps={{
                            showSearch: true,
                            options: agentList,
                            onChange: (value: number) => {
                                getAuthCode(value);
                            }
                        }}
                    />}
                    {deviceType === 3 && <ProFormSelect
                        width={'md'}
                        name="hwareVersion"
                        label={'硬件版本'}
                        disabled={isDetail}
                        rules={[
                            {
                                required: true,
                                message: '请选择硬件版本'
                            }
                        ]}
                        fieldProps={{
                            showSearch: true,
                            options: modelType === 4 ? hardwareVersion.slice(-1) : hardwareVersion,
                            onChange: (value: string) => {
                                setHwareVersion(value);
                            }
                        }}
                    />}
                    {deviceType === 3 && <ProFormSelect
                        width={'md'}
                        name="currentSelectedCode"
                        label={'格口使用编码'}
                        disabled={isDetail}
                        rules={[
                            {
                                required: true,
                                message: '请选择代理商名称'
                            }
                        ]}
                        fieldProps={{
                            showSearch: true,
                            options: cellCodeTypeData,
                        }}
                        addonAfter={<QuestionCircleOutlined style={{ color: '#1890ff', fontSize: 20 }} onClick={() => {
                            setExplain_visible(true);
                        }} />}
                    />}
                    {deviceType === 3 && +cur_hwareVersion > 4 && <ProFormSelect
                        width={'md'}
                        name="mainboard"
                        label={'主板'}
                        disabled={isDetail}
                        rules={[
                            {
                                required: true,
                                message: '请选择主板名称'
                            }
                        ]}
                        fieldProps={{
                            showSearch: true,
                            options: mainBoardData,
                        }}
                    />}
                    {deviceType === 3 && <ProFormText
                        width={'md'}
                        name="code"
                        label={'柜体编号'}
                        disabled={true}
                        addonAfter={isCreate && <Button type={"default"} onClick={() => {
                            formRef?.current?.setFieldValue('code', '');
                        }}>自定义</Button>}
                    />}

                    {deviceType === 3 && <ProFormText
                        width={'md'}
                        name="authCode"
                        label={'授权码'}
                        disabled={true}
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                        addonAfter={<Button type={"default"} onClick={() => {
                            const val = formRef?.current?.getFieldValue('authCode');
                            console.log(val);
                            $utils.copyCot(val);
                        }}>复制</Button>}
                    />}
                    <ProFormText
                        width={'md'}
                        name="remark"
                        label={'添加原因'}
                        disabled={isDetail}
                        fieldProps={{
                            maxLength: 300,
                        }}
                        rules={[
                            {
                                required: true,
                            }
                        ]}
                    />
                    {isDetail && <ProFormText
                        width={'md'}
                        name="stationName"
                        label={'归属驿站'}
                        disabled={isDetail}
                        fieldProps={{
                            maxLength: 300,
                        }}
                        rules={[
                            {
                                required: true,
                            }
                        ]}
                    />}
                </ProForm>
            </ProCard>}
            <Modal
                width={500}
                title={<div style={{ textAlign: 'center' }}>说明</div>}
                footer={null}
                open={explain_visible}
                onCancel={() => {
                    setExplain_visible(false);
                }}
                maskClosable={true}>
                <Typography>
                    <Paragraph>格口编码：</Paragraph>
                    <Paragraph style={{ marginBottom: '0.5em' }}>1.硬件版本选择1.0、2.0、3.0版本，格口编码仅可选择默认或旧编码。</Paragraph>
                    <Paragraph style={{ marginBottom: '0.5em' }}>2.硬件版本选择4.0版本，根据实际柜体情况选择格口编号，默认为旧编码，也可以选择新编码。</Paragraph>
                    <Paragraph>3.硬件版本选择5.0、6.0版本，格口编码仅可选择默认或新编码。</Paragraph>
                </Typography>
            </Modal>
        </PageContainer>
    );
};

export default Detail;
